/**
 * Created with JetBrains WebStorm.
 * User: zhaoyanchao
 * Date: 13-7-6
 * Time: 上午10:47
 * To change this template use File | Settings | File Templates.
 */
var http = require('http');
    mysql = require('mysql'),
    config = require('./config').config;
function getWeather(options, connectCallback,errorCallback) {

    var req = http.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('error', function (e) {
            console.log('error: '+e)
        }).on('data', function (chunk) {
               connectCallback(chunk);
            })
    });
    req.end();
}

function getWeatherBuffers(options,callback){
    var req = http.request(options, function (res) {
        var rec_leng = 0;
        var rec_ary = [];
        res.on('error', function (e) {
            console.log('err'+e)
        }).on('data',function(chunk){
                rec_leng += chunk.length;
                rec_ary.push(chunk);
            }).on('end',function(){
                var buf = Buffer.concat(rec_ary,rec_leng);
                var result = buf.toString();
                callback(result)
            })
    });
    req.end();
}

function getAlarmCityCode(url,callback){
    var url_arr = url.split('-');
     if(url_arr[0].length == 7){
         var connection = mysql.createConnection(config.app_weibo);
         connection.connect();
         var sql = "SELECT cityCode FROM app_weibo.cityInfo WHERE cityCode LIKE '%"+url_arr[0]+"%'";
         connection.query(sql,function(err,rows){
             if(err) throw err;
             callback(rows)
             connection.end();
         })
     }
}

//var url ='10106-20130708173547-0201.html';
//var url2 ='1012212-20130709100135-0703.html';
//
//getAlarmCityCode(url,function(data){
//    console.log(data);
//});

//var options = {
//    hostname: 'weather.com.cn',
//    port: 80,
//    path: '/data/alarm/1011813-20130708211319-0202.html',
//    method: 'GET'
//}
//getWeatherBuffers(options,function(data){
//    console.log(data)
//})

//var options = {
//    hostname: 'www.weather.com.cn',
//    port: 80,
//    path: '/data/sk/101010300.html',
//    method: 'GET'
//};
//getWeather(options,function(data){
//    console.log(data)
//})

exports.getWeather =getWeather
exports.getWeatherBuffers =getWeatherBuffers
exports.getAlarmCityCode =getAlarmCityCode
